package com.obggtc.picture.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.unit.DataSize;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.MultipartConfigElement;

/**
 *
 * 静态资源映射
 */
@Configuration
public class WebConfig implements WebMvcConfigurer {

 @Autowired
 private PathConfig pathConfig;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        String os = System.getProperty("os.name");
        if (os.toLowerCase().startsWith("win")) {
            // 图片资源映射
            registry.addResourceHandler("/static/img/**").addResourceLocations("file:" + pathConfig.getWinPath());
            // 视频资源映射
            registry.addResourceHandler("/static/video/**").addResourceLocations("file:" + pathConfig.getWinVideoPath());
        } else {
            // 图片资源映射
            registry.addResourceHandler("/static/img/**").addResourceLocations("file:" + pathConfig.getLinuxPath());
            // 视频资源映射
            registry.addResourceHandler("/static/video/**").addResourceLocations("file:" + pathConfig.getLinuxVideoPath());
        }
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
            .allowedOriginPatterns("*")  // 使用 allowedOriginPatterns 代替 allowedOrigins
            .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
            .allowedHeaders("*")
            .allowCredentials(true)
            .maxAge(3600);
    }
    
    /**
     * 配置multipart文件上传
     */
    @Bean
    public MultipartConfigElement multipartConfigElement() {
        MultipartConfigFactory factory = new MultipartConfigFactory();
        // 设置文件大小限制
        factory.setMaxFileSize(DataSize.ofMegabytes(100)); // 100MB
        factory.setMaxRequestSize(DataSize.ofMegabytes(100)); // 100MB
        return factory.createMultipartConfig();
    }
}
